package com.example.examsystem.repository;

import com.example.examsystem.model.Question;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 试题数据访问层
 */
@Repository
public interface QuestionRepository extends JpaRepository<Question, Long> {
    
    /**
     * 根据学科ID统计试题数量
     */
    long countBySubjectId(Long subjectId);
    
    /**
     * 根据分类ID统计试题数量
     */
    long countByCategoryId(Long categoryId);
    
    /**
     * 根据题型查找试题
     */
    List<Question> findByType(String type);
    
    /**
     * 根据难度查找试题
     */
    List<Question> findByDifficulty(Integer difficulty);
    
    /**
     * 分页查询试题（支持多条件筛选）
     */
    @Query("""
       SELECT q FROM Question q
       WHERE
           (:query IS NULL OR :query = '' 
               OR LOWER(q.title) LIKE LOWER(CONCAT('%', :query, '%')) 
               OR LOWER(q.content) LIKE LOWER(CONCAT('%', :query, '%'))) 
           AND (:type IS NULL OR :type = '' OR q.type = :type) 
           AND (:difficulty IS NULL OR q.difficulty = :difficulty) 
           AND (:subjectId IS NULL OR q.subjectId = :subjectId) 
           AND (:categoryId IS NULL OR q.categoryId = :categoryId)
       """)
    Page<Question> findByQueryWithFilters(@Param("query") String query,
                                         @Param("type") String type,
                                         @Param("difficulty") Integer difficulty,
                                         @Param("subjectId") Long subjectId,
                                         @Param("categoryId") Long categoryId,
                                         Pageable pageable);
}






